package com.bw.educate.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.educate.common.tree.TreeCategory;
import com.bw.educate.common.tree.TreeChapter;
import com.bw.educate.entity.EduCategoryChild;
import com.bw.educate.entity.EduCourseChapter;
import com.bw.educate.entity.EduCourseSection;
import com.bw.educate.mapper.EduCourseChapterMapper;
import com.bw.educate.mapper.EduCourseSectionMapper;
import com.bw.educate.service.IEduCourseChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 在线教育-五组
 * @since 2020-08-12
 */
@Service
public class EduCourseChapterServiceImpl extends ServiceImpl<EduCourseChapterMapper, EduCourseChapter> implements IEduCourseChapterService {

    @Resource
    private EduCourseSectionMapper courseSectionMapper;

    @Override
    public List<TreeChapter> getTree(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("COURSE_ID",id);
        List<EduCourseSection> SectionList = courseSectionMapper.selectList(queryWrapper);

        List<TreeChapter> list = new ArrayList<>();

        for (EduCourseSection se:SectionList){
            String s = JSON.toJSONString(se);
            TreeChapter treeChapter = JSON.parseObject(s, TreeChapter.class);
            list.add(treeChapter);
        }

        return buildTree(list);
    }

    @Override
    public void delTree(Long id) {
        //删除id章
        courseSectionMapper.deleteById(id);
        //删除节
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("CHAPTER_ID",id);
        courseSectionMapper.delete(queryWrapper);
    }


    //把一个list转换为树
    public List<TreeChapter> buildTree( List<TreeChapter> treeChapterList){
        List<TreeChapter> tree = new ArrayList<>();

        for (TreeChapter ca:treeChapterList) {
            if(ca.getChapterId()==0){
                tree.add(findChild(ca,treeChapterList));
            }
        }
        return tree;
    }

    TreeChapter findChild(TreeChapter node,List<TreeChapter> treeChapterList){
        for (TreeChapter ca:treeChapterList) {
            if(ca.getChapterId().equals(node.getId())){
                if (node.getChildren()==null){
                    node.setChildren(new ArrayList<>());
                }
                node.getChildren().add(ca);
            }
        }
        return node;
    }



}
